<template>
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        :formProp="formData"
        @search="search"
        :isShowSearch="isShowSearch"
        @change="change"
        class="ccui-highsearch"
        :selectClear="true"
      >
        <div class="ccui-tab-wrapper">
          <el-button :type="'table-top-active'" size="mini">
            <template>全部 ({{ totalNum }})</template>
          </el-button>
        </div>
        <el-export-button
          class="export-button"
          @export-excel="exportExcel"
          @export-pdf="exportPdf"
          style="display: inline-block; position: absolute; right: 0; top: 0"
        ></el-export-button>
        <template slot="search">
          <el-input
            v-model="formData.settlementName"
            clearable
            searchLabel="结算单名称"
            placeholder="请输入结算单名称模糊查询"
            @blur="handleTrim('settlementName')"
          ></el-input>
          <el-input
            v-model="formData.settlementCode"
            clearable
            searchLabel="结算单编号"
            placeholder="请输入结算单编号模糊查询"
            @blur="handleTrim('settlementCode')"
          ></el-input>
          <el-input
            v-model="formData.contractCode"
            clearable
            searchLabel="合同编号"
            placeholder="请输入合同编号模糊查询"
          ></el-input>
          <el-input
            v-model.trim="formData.formalContractCode"
            clearable
            searchLabel="合同正式编号"
            placeholder="请输入合同正式编号模糊查询"
          />
          <el-date-picker
            v-model="formData.paymentApplyDate"
            searchLabel="结算期间"
            :clearable="false"
            align="right"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
          <el-input
            v-model="formData.supplierName"
            clearable
            searchLabel="供应商"
            placeholder="请输入供应商模糊查询"
            @blur="handleTrim('supplierName')"
          ></el-input>
        </template>
        <!-- 表单高级搜索 -->
        <el-input
          v-model="formData.settlementName"
          clearable
          searchLabel="结算单名称"
          placeholder="请输入结算单名称模糊查询"
          slot="searchItem1"
          @blur="handleTrim('settlementName')"
        />
        <el-input
          v-model="formData.settlementCode"
          clearable
          searchLabel="结算单编号"
          placeholder="请输入结算单编号模糊查询"
          slot="searchItem2"
          @blur="handleTrim('settlementCode')"
        />
        <el-input
          v-model="formData.contractCode"
          clearable
          searchLabel="合同编号"
          placeholder="请输入合同编号模糊查询"
          slot="searchItem3"
          @blur="handleTrim('contractCode')"
        />
        <el-input
          v-model.trim="formData.formalContractCode"
          clearable
          searchLabel="合同正式编号"
          placeholder="请输入合同正式编号模糊查询"
          slot="searchItem4"
        />
        <el-date-picker
          v-model="formData.paymentApplyDate"
          :clearable="false"
          searchLabel="结算期间"
          align="right"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          slot="searchItem5"
        />
        <el-input
          v-model="formData.supplierName"
          clearable
          searchLabel="供应商"
          slot="searchItem6"
          placeholder="请输入供应商模糊查询"
          @blur="handleTrim('supplierName')"
        />
      </el-search>
    </div>
    <!-- 表格 -->
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        ref="multipleTable"
        :data="tableData"
        :row-style="rowClass"
        border
        class="ccui-multifunctional-table"
        @header-dragend="tableTitleWidth"
        @sort-change="sortChange"
        max-height="9999"
        v-if="draggFlag"
      >
        <el-table-column label="序号" width="50" :fixed="true">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="结算单编号"
          width="150"
          :fixed="true"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span
              :style="{ color: 'rgb(0, 137, 239)', cursor: 'pointer' }"
              @click="handleGoDetail(scope.row, 1)"
              >{{ scope.row.settlementCode }}</span
            >
          </template>
        </el-table-column>
        <template v-for="(table, i) in unfixedTableThead">
          <el-table-column
            :fixed="table.fixed || false"
            :type="table.type"
            :key="'two' + i"
            :label="table.label"
            :align="table.align || 'left'"
            :header-align="table.headerAlign || 'left'"
            :min-width="table.width"
            :prop="table.prop"
            :show-overflow-tooltip="true"
            border="true"
          >
          </el-table-column>
        </template>
      </el-table>
      <div class="ccui-table-footer" v-show="isShowPagination">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="pageSizeCode"
            background
            :current-page="pageNoCode"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleSizeChange('none')"
            >确定</el-button
          >
        </div>
      </div>
    </div>
    <!-- 表格end -->
  </div>
</template>

<script>
import {
  setSessionItem,
  getSessionItem,
  removeSessionItem,
  ishasAgentId
  // addUrlPerFix
} from "@/basa/utils";
import {
  listSettlementPage
  // accountExport
} from "../../settlement-maintenance-approval/api/settlement-approval";
import { detailExport } from "@/basa/api";
import { exportData } from "@/basa/utils/public";
export default {
  name: "settlement-standing-all",
  data() {
    return {
      isActive: 0,
      isShowDetail: true,
      isShowEdit: true,
      multiDataToEnd: {},
      singleDataToEnd: {},
      draggFlag: true,
      // 表格相关
      tableData: [],

      tableName: this.tableList.settlementStandingBook, // 表格命名
      tableThead: [],

      fixedTableThead: [],
      // 非锁定表格
      unfixedTableThead: [
        {
          label: "结算单名称",
          prop: "settlementName",
          width: "180"
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "180"
        },

        {
          label: "合同编号",
          prop: "contractCode",
          width: "120",
          resizable: false
        },
        {
          label: "合同正式编号",
          prop: "formalContractCode",
          width: "150"
        },
        {
          label: "合同名称",
          prop: "contractName",
          width: "120"
        },
        {
          label: "供应商",
          prop: "supplierName",
          width: "120"
        },
        {
          label: "结算数量",
          prop: "currSetCount",
          width: "120",
          resizable: false
        },
        {
          label: "结算金额",
          prop: "currSetMoney",
          width: "120",
          align: "right"
        },
        {
          label: "单据状态",
          prop: "settlementStatus",
          width: "120"
        }
      ],
      unfixedTableTheadTow: [],
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      // popoverShow: false,
      selectRow: [],
      selectData: [],
      isFocus: 1,
      // 表格相关 end
      // 高级搜索数据 start
      formData: {
        changeCode: "",
        changeName: "",
        declareDate: "",
        declareAmount: "",
        replyDate: "",
        replyAmount: "",
        contractStatus: "",
        jsdate: ""
      }, // 高级搜索提交数据
      formDataSearch: {},
      localSearchData: {},
      isShowSearch: true,
      isShow: false,
      // 高级搜索数据 end
      isShowPagination: false, //无数据的不展示底部全选，批量删除
      // 全选以及页码
      totalNum: 0,
      total: 0,
      isIndeterminate: false,
      checkAll: false,
      value: "",
      pageNoCode: this.getLocalPageNo(),
      pageSizeCode: 10,
      // isFist: false,
      // 全选以及页码 end
      // 表格数据删除相关
      delDemoId: "",
      content: "制表单位/制表人/日期：中交信科/游欢欢 2021.06.01",
      typeDel: "", //有关批量删除
      isSelection: false,
      // 表格数据删除相关 end
      // 排序入参所需字段
      sortord: "",
      sortprop: "",
      excelData: [],
      // 表格数据相关处理 end
      form: {}
    };
  },
  computed: {},
  watch: {},
  methods: {
    //去空格
    handleTrim(key) {
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    },
    // 查看
    handleGoDetail(row, i) {
      // 维护的详情页
      this.$router.push({
        path: `/settlement-management/settlement-maintenance-approval/settlement-check-approval/${row.id}`
      });
    },
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    //导出当前
    exportExcel() {
      let formDataSearch = JSON.parse(JSON.stringify(this.formDataSearch));
      delete formDataSearch.isShowPageLoading;
      detailExport({
        ...formDataSearch,
        type: "settlement/accountExport"
      }).then(res => {
        exportData(res);
      });
    },
    // 导出全部
    exportPdf() {
      let formDataSearch = JSON.parse(JSON.stringify(this.formDataSearch));
      console.log(formDataSearch);
      formDataSearch.pageNo = 1;
      formDataSearch.pageSize = 3000;
      delete formDataSearch.isShowPageLoading;

      detailExport({
        ...formDataSearch,
        type: "settlement/accountExport"
      }).then(res => {
        exportData(res);
      });
    },
    // 新增
    handleGoNew() {
      this.$router.push(
        "/settlement-management/settlement-written-off/settlement-new"
      );
    },

    initData() {
      this.isShow = false;
      this.setTableWidth();
    },

    // 表格弹框拖拽触发
    handleTableChange(val) {
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 是否显示对应列
    handleUpdate(item, index) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (i === index) {
          this.unfixedTableThead.checked = !this.unfixedTableThead.checked;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },

    // 上一页
    handlePrev() {
      console.log("上一页");
    },
    // 下一页
    handleNext() {
      console.log("下一页");
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    },
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = searchData;
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      console.log("121212121", this.formDataSearch);
      this.getList(this.formDataSearch);
    },
    // 高级搜索 end

    // 列表数据请求
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.paymentState = this.paymentState;
      obj.settlementStart = obj.paymentApplyDate ? obj.paymentApplyDate[0] : "";
      obj.settlementEnd = obj.paymentApplyDate ? obj.paymentApplyDate[1] : "";
      obj.settlementStatus = "5,22";
      this.listSettlementPage(obj);
    },
    //列表接口
    listSettlementPage(obj) {
      listSettlementPage(obj).then(res => {
        this.tableData = res.data.data.rows;
        this.tableData.forEach(item => {
          item.statusCode = item.settlementStatus;
          item.currSetMoney =
            item.currSetMoney !== null ? item.currSetMoney.toFixed(2) : "";
          item.currSetCount =
            item.currSetCount !== null ? item.currSetCount.toFixed(3) : "";
          if (item.settlementStatus == "2") {
            item.settlementStatus = "编辑中";
          } else if (item.settlementStatus == "3") {
            item.settlementStatus = "审批中";
          } else if (item.settlementStatus == "4") {
            item.settlementStatus = "已撤回";
          } else if (item.settlementStatus == "5") {
            item.settlementStatus = "审批通过";
          } else if (item.settlementStatus == "6") {
            item.settlementStatus = "审批退回";
          } else if (item.settlementStatus == "7") {
            item.settlementStatus = "审批不通过";
          } else if (item.settlementStatus == "9") {
            item.settlementStatus = "已生效";
          } else if (item.settlementStatus == "11") {
            item.settlementStatus = "已删除";
          } else if (item.settlementStatus == "21") {
            item.settlementStatus = "冲销中";
          } else if (item.settlementStatus == "22") {
            item.settlementStatus = "已冲销";
          }
        });
        this.excelData = this.tableData;

        this.totalNum = res.data.data.recordsTotal;
        if (this.totalNum > 0) {
          this.isShowPagination = true;
        }
      });
    },

    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection();
      const arr = [];
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
          arr.push(row.id);
        });
        this.idArrSelected = arr;
      }
    },
    // 排序
    sortChange(params) {
      this.sortord = params.order;
      this.sortprop = params.prop;
      this.getList();
    },
    // 默认显示多少条
    getLocalPageSize() {
      return (
        getSessionItem("pageSize", this.tableList.settlementWrittenOffAll) || 10
      );
    },
    // 读取当前页缓存
    getLocalPageNo() {
      let localData = getSessionItem(
        "pageNo",
        this.tableList.settlementWrittenOffAll
      );
      return (localData && localData.pageNo) || 1;
    }
  },

  mounted() {
    this.initData();
  },
  beforeRouteLeave(to, from, next) {
    removeSessionItem("pageNo");
    for (var key in this.$vnode.parent.componentInstance.cache) {
      delete this.$vnode.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    next();
  },
  activated() {
    if (Object.keys(this.localSearchData).length > 0) {
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
    }
    let localData = getSessionItem(
      "pageNo",
      this.tableList.settlementWrittenOffAll
    );
    let data = localData && localData.searchForm;
    this.getList({ ...this.formDataSearch, ...data });
  }
};
</script>
<style lang="scss" scoped>
/deep/ .el-searchs {
  margin-right: 72px;
}
</style>
